2  First steps in R

Here we assume you have R installed on your computer and you know how to use it interactively.

Simple arithmetic

The arithmetic operators are

  • Addition: +
  • Subtraction: -
  • Multiplication: * (not x)
  • Division: /
  • Exponentiation: ^

With these, you can use the R interpreter as a calculator.

You can run the following expressions in the R interpreter. The interpreter will evaluate them and return the value.

1 + 2 + 3
[1] 6
2 * 3 - 5
[1] 1
1/2 + 1/4
[1] 0.75
5^2
[1] 25

In addition to arithmetic operators, R can evaluate many common mathematical functions, such as sqrt for square root:

sqrt(25)
[1] 5
Exercise

Evaluate the following expressions.

  • \(\frac{1}{2} + \frac{2}{3} + \frac{3}{4}\)

  • \(\frac{1 + 2/3}{3 - 1/(2/3)}\)

  • \(1 + \frac{1}{1 + \frac{1}{1 + \frac{1}{2}}}\)

  • \(\sqrt{17.4^2 + 3.67^2 - 9.12^2}\)

Variable assignment

A very basic feature of programs is that you can assign names to some values, and then use that name over and over.

x <- 10 # Read: "x gets 10"

We can verify that x has the assigned value:

x
[1] 10

We can always assign a new value to x.

x <- 11
x
[1] 11

The following statement updates the value of x. First, the right-hand side is evaluated. The resulting value is assigned as a new value to x.

x <- x + 1
x
[1] 12
Exercise

Given the variables

account_balance <- 1000
interest_rate <- 0.10

update the variable account_balance by adding the interest.

account_balance <- 1000
interest_rate <- 0.10
# write your update below (1 line)
...
# end of your code
account_balance
Exercise

Given the variables

account_balance <- 1000
interest_rate <- 0.10

find the value of the account_balance after 5 update periods.

account_balance <- 1000
interest_rate <- 0.10
# write your code lines below (5 lines)
...
# end of your code
account_balance
Example

Assignments can be more complex, and may involve many variables. Consider the follwoign example:

Every year, 1% of the people living in city A move to city B, and 2% of people living in city B move to city A. If the current populations of city A and city B are 10000 and 20000, respectively, find the populations of both cities next year.

# Initialize variables
cityA <- 10000
cityB <- 20000

# Update variables
cityA_next <- cityA + 0.02*cityB - 0.01*cityA
cityB_next <- cityB + 0.01*cityA - 0.02*cityB
cityA <- cityA_next
cityB <- cityB_next

# Display new values
cityA
[1] 10300
cityB
[1] 19700

Note that we used intermediate variables cityA_next and cityB_next, instead of directly updating like cityA <- cityA + 0.02*cityB - 0.01*cityA. Why would a direct update be a mistake? Try rerunning your program with this mistake and compare the results.